﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using b7.Models;

namespace b7.Controllers
{

    public class AccountController : Controller
    {
        private b7Models db = new b7Models();
        /// <summary>
        /// Acction su ly phuong thuc get ("thuong la cac link cac ban click vao hoac cac form truyen du lieu kieu get")
        /// </summary>
        /// <returns>sau khi su ly thi return mot trang web(nap lai web cho client)</returns>
        [HttpGet]//phuong thuc get
        public ActionResult LogOn()
        {
            return View("LogOn"); //nap giao dien trang logOn cho client
        }

        /// <summary>
        /// Acction su ly phuong thuc post("thuong la cac cac ban clik vao nut dang nhap cua mot form de chuyen du lieu len server theo kieu post")
        /// </summary>
        /// <param name="model">du lieu tai khoan va pass duoc gui len tu client</param>
        /// <param name="returnUrl">link trang de quay lai khi dang nhap xong</param>
        /// <returns>sau khi su ly: thanh cong se hien thi trang Home,neu dang nhap sai thi Hien trang logOn va loi~</returns>
        [HttpPost]//phuong thuc post 
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)//kiem tra validate cua du lieu("chi tiet thi vao Models Class:LogOnModel ma xem")
            {
                ////------------------Kiem tra tai khoan co o trong database khong?-------------------------
                ////o day minh dung phuong thuc Entities de ket noi toi database.cac ban co the dung cach khac de ket noi toi database
                //LoginAccountEntities db = new LoginAccountEntities(); //khoi tao lop ket noi toi database
                List<Member> accounts = db.Members.Where(x => x.UserName.Equals(model.UserName) && x.Password.Equals(model.Password)).ToList(); //no tuong tu nhu cau lenh "Select * From Accounts Where NameAccount = @model.UserName and Password = @model.Password
                ////----------------------------------------------------------------------------------------
                if (accounts.Count>0)//kiem tra xem co tim thay tai khoan do khong?
                {
                    MigrateShoppingCart(model.UserName);
                    //// Neu tim thay
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); //goi ham nay no se goi phuong thuc GetRolesForUser(string username) o file CustomRoleProvider.cs
                    //// model.UserName o day la chuyen tai khoan nay vao de lay ra quyen cua tai khan do,model.RememberMe la co luu vao coockie hay khong? cai o vuong ma ban danh dau co luu tai khoan ay!(cai trang LogOn)
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))//doan code nay nham muc dich khi ma ban vao mot trang nao do mo khong dung quyen han no se bat ban dang nhap.neu thanh cong no se tro lai trang truoc do ma ban muon vao.
                    {
                        return Redirect(returnUrl); //tro lai trang truoc do ma ban muon vao
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home"); //chuyen sang trang Index cua controllers Home.
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Sai tai khoan hoac mat khau."); //neu khong tim thay tai khoan thi hien thi loi sai tai khoan
                }
            }

            // neu cac ban nhap cu phap account hoac pass no se nap lai trang LogOn va hien thi loi~
            return View("LogOn",model);//o day them vao model la de nap lai cac gia tri cac ban nham vao.neu khong co model thi khi nap lai trang cac du lieu o cac o account hoac pass se mat(value ="")
        }

        /// <summary>
        /// Acction su ly phuong thuc get(su ly khi ban clik vao link LogOff)
        /// </summary>
        /// <returns>Sau khi su ly xong thi nap lai mot trang web cho client</returns>
        [HttpGet]//phuong thuc get
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();//xoa du lieu quyen va tai khoan
            return RedirectToAction("Index", "Home");//nap lai trang home cho client
        }

        /// <summary>
        /// Acction su ly phuong thuc get(su ly khi ban clik vao link Dang Ky)
        /// </summary>
        /// <returns>nap trang dang ky cho client</returns>
        [HttpGet]//phuong thuc get
        public ActionResult Register()
        {
            return View("Register");//nap giao dien trang dang ky cho client
        }

        /// <summary>
        /// Acction su ly phuong thuc get(su ly khi ban clik vao nut dang ky o form Dang Ky(trong trang dang ky))
        /// </summary>
        /// <param name="model">du lieu ma client gui len</param>
        /// <returns>khi su ly xong se nap giao dien cua mot trang web</returns>
        [HttpPost]//phuong thuc post
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)//kiem tra cu phap cua du lieu.("Xem chi tiet o Models class:RegisterModel")
            {
                //// Neu thoa man du lieu thi kiem tra xem tai khoan nay da co trong db chua?
                ////--------------------------thao tac voi db---------------------------
                //LoginAccountEntities db = new LoginAccountEntities(); //tao ket noi voi database
                List<Member> accounts = db.Members.Where(x => x.UserName.Equals(model.UserName)).ToList();//tuong dong voi cau lenh "Select * From Accounts Where Accounts = @model.UserName"
                ////--------------------------------------------------------------------
                if (accounts.Count == 0) //kiem tra xem tai khoan do da ton tai chua
                {
                    ////neu chua ton tai thi insert vao trong database
                    ////--------------------------thao tac voi db---------------------------
                    Member account = new Member();//khoi tao mot doi tuong Account ("Mot dong` du lieu trong database")
                    account.Role = "adminshop"; //gan quyen
                    account.UserName = model.UserName; //gan tai khoan 
                    account.FullName = model.FullName;
                    account.Email = model.Email;
                    account.Password = model.Password; //gan mat khau
                    account.Ngaysinh = model.Ngaysinh;
                    account.Sex = model.Sex;
                    account.CMTND = model.CMTND;
                    account.Adress = model.Adress;
                    account.PhoneNumber = model.PhoneNumber;
                    db.Members.Add(account);// tuong duong voi dong lenh: "INSERT INTO Accounts([NameAccount],[Password],[Roles])VALUES(@account.NameAccount,@account.Password,@account.Roles)"
                    db.SaveChanges(); // tuong duong voi executequery
                    ////--------------------------------------------------------------------
                    MigrateShoppingCart(model.UserName);
                    FormsAuthentication.SetAuthCookie(model.UserName, false);//khi dang ky xong thi dang nhap luon nhung khong luu vao cookie
                    return RedirectToAction("Index", "Home"); //nap trang Home cho client
                }
                else
                {
                    ModelState.AddModelError("", "tai khoan nay da ton tai");//add them thong bao
                }
            }
            //// neu nhap sai cu phap thi se nap lai trang dang ky va hien thi loi~
            return View("Register",model);//nap lai trang Dang Ky cho client
        }

        [HttpGet]//phuong thuc get
        public ActionResult RegisterMember()
        {
            return View("RegisterMember");//nap giao dien trang dang ky cho client
        }
        [HttpPost]//phuong thuc post
        public ActionResult RegisterMember(RegisterMemberModel model)
        {
            if (ModelState.IsValid)//kiem tra cu phap cua du lieu.("Xem chi tiet o Models class:RegisterModel")
            {
                //// Neu thoa man du lieu thi kiem tra xem tai khoan nay da co trong db chua?
                ////--------------------------thao tac voi db---------------------------
                //LoginAccountEntities db = new LoginAccountEntities(); //tao ket noi voi database
                List<Member> accounts = db.Members.Where(x => x.UserName.Equals(model.UserName)).ToList();//tuong dong voi cau lenh "Select * From Accounts Where Accounts = @model.UserName"
                ////--------------------------------------------------------------------
                if (accounts.Count == 0) //kiem tra xem tai khoan do da ton tai chua
                {
                    ////neu chua ton tai thi insert vao trong database
                    ////--------------------------thao tac voi db---------------------------
                    Member account = new Member();//khoi tao mot doi tuong Account ("Mot dong` du lieu trong database")
                    account.Role = "member"; //gan quyen
                    account.UserName = model.UserName; //gan tai khoan 
                    account.FullName = "ismember";
                    account.Email = model.Email;
                    account.Password = model.Password; //gan mat khau
                    account.Ngaysinh = model.Ngaysinh;
                    account.Sex = model.Sex;
                    account.CMTND = "111111111";
                    account.Adress = model.Adress;
                    account.PhoneNumber = model.PhoneNumber;
                    db.Members.Add(account);// tuong duong voi dong lenh: "INSERT INTO Accounts([NameAccount],[Password],[Roles])VALUES(@account.NameAccount,@account.Password,@account.Roles)"
                    db.SaveChanges(); // tuong duong voi executequery
                    ////--------------------------------------------------------------------
                    FormsAuthentication.SetAuthCookie(model.UserName, false);//khi dang ky xong thi dang nhap luon nhung khong luu vao cookie
                    return RedirectToAction("Index", "Home"); //nap trang Home cho client
                }
                else
                {
                    ModelState.AddModelError("", "tai khoan nay da ton tai");//add them thong bao
                }
            }
            //// neu nhap sai cu phap thi se nap lai trang dang ky va hien thi loi~
            return View("RegisterMember", model);//nap lai trang Dang Ky cho client
        }

        private void MigrateShoppingCart(string UserName)
        {
            // Associate shopping cart items with logged-in user
            var cart = ShoppingCart.GetCart(this.HttpContext);

            cart.MigrateCart(UserName);
            Session[ShoppingCart.CartSessionKey] = UserName;
        }
    }
}
